package com.chinaunicom.create.singleton.hungry;

import java.util.Random;

/**
 * @author liry
 * @version 1.0
 * @date Created on 2022/7/14 14:22
 * Description: 懒汉式(同步代码块)
 */
public class HSingleton03 {

    private static HSingleton03 instance;

    private HSingleton03() {
    }


    // 在方法上添加 同步关键字
    public static HSingleton03 getInstance() {

        if (instance == null) {
            // 同步代码块
            synchronized (HSingleton03.class) {
                instance = new HSingleton03();
            }
        }
        return instance;
    }


    public static void main(String[] args) {
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
//                       Thread.sleep(random.nextInt(100));
                        System.out.println(HSingleton03.getInstance().toString());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }, "Thread name: " + i).start();
        }

    }
}
